package get_advertiser_fund_daily_stat

import (
	oceanApi "cid-media-api/api/ocean"
	"cid-media-api/global"
	"cid-media-api/models"
	. "github.com/oceanengine/ad_open_sdk_go/models"
	"github.com/robfig/cron/v3"
	"github.com/samber/lo"
	"log"
	"sync"
	"time"
)

func Run() {
	c := cron.New()
	c.AddFunc("*/2 * * * *", func() { //TODO 获取账户日流水 配置执行的确切时段

		startTime := time.Now().Format(time.DateTime)
		log.Printf("====================================================")
		log.Printf("正在定时执行账户日流水获取任务")
		log.Printf("任务开始时间： %v", startTime)

		Execute(0, time.Now().Format(time.DateOnly), time.Now().Format(time.DateOnly))

		endTime := time.Now().Format(time.DateTime)
		log.Printf("任务结束时间： %v", endTime)
		log.Printf("====================================================")

	})

	c.Run()
}

func Execute(advertiserID int, startDate string, endDate string) []*AdvertiserFundDailyStatV2ResponseData {
	var mediaAccounts []models.MediaAccount

	db := global.CidDb.Where("status = ?", 1).Where("media_id = ?", oceanApi.MediaIdOcean)

	if advertiserID > 0 {
		db = db.Where("advertiser_id = ?", advertiserID)
	}

	err := db.Find(&mediaAccounts).Error

	if err != nil {
		print(err)
	}

	var result []*AdvertiserFundDailyStatV2ResponseData

	const chunkSize = 800 //分批处理
	for _, accountBatches := range lo.Chunk(mediaAccounts, chunkSize) {
		var apiBatchData []*AdvertiserFundDailyStatV2ResponseData
		apiBatchDataChan := make(chan *AdvertiserFundDailyStatV2ResponseData)
		var wg sync.WaitGroup

		for _, account := range accountBatches {
			wg.Add(1)
			go func() {
				data := oceanApi.GetAdvertiserFundDailyStat(account, startDate, endDate)

				if data == nil {
					return
				}

				apiBatchDataChan <- data
			}()
		}

		go func() {
			for range accountBatches {
				select {
				case item := <-apiBatchDataChan:
					apiBatchData = append(apiBatchData, item)
					wg.Done()
				}
			}
		}()

		wg.Wait()

		result = append(result, apiBatchData...)
	}

	return result

	//TODO 入库

}
